/**
 * 测试1000和1020指令教派信息修复效果（模拟有教派信息的情况）
 * 基于test-faction-fix.js修改，模拟用户有教派信息的情况
 */

const http = require('http');
const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'http'
    },

    // 测试用户信息 - 使用玩家2001
    testUser: {
        mobile: '17091271112',
        password: '123456',
        passwordHash: 'e10adc3949ba59abbe56e057f20f883e'
    }
};

class FactionWithReligionTester {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
        this.selectedCharacter = null;
        this.testResults = [];
        this.code1000Data = null;
        this.code1020Data = null;
    }

    // 运行完整测试流程
    async runTest() {
        console.log('🚀 开始测试1000和1020指令教派信息修复效果（模拟有教派信息）...\n');
        console.log('测试目标：验证1000和1020指令都能正确返回教派信息\n');

        try {
            // 1. HTTP登录
            await this.testHttpLogin();

            // 2. 建立WebSocket连接
            await this.testWebSocketConnection();

            // 3. 查询角色列表
            await this.testQueryCharacters();

            // 4. 选择角色（优先选择ID为2001的角色）
            await this.testSelectCharacter();

            // 5. 测试1000指令 - 角色信息查询
            await this.testCode1000CharacterInfo();

            // 6. 测试1020指令 - 玩家完整信息查询
            await this.testCode1020PlayerInfo();

            // 7. 验证教派信息返回
            await this.validateFactionInfo();

            // 8. 断开连接
            await this.testDisconnect();

            // 输出测试结果
            this.printTestResults();

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
            this.addTestResult('整体测试', false, error.message);
        }
    }

    // 1. HTTP登录测试
    async testHttpLogin() {
        console.log('🔐 步骤1: HTTP登录测试...');

        try {
            // 执行登录
            const loginData = await this.makeHttpRequest('/user-service/user/login', 'POST', {
                mobile: CONFIG.testUser.mobile,
                pwd: CONFIG.testUser.password
            });

            if (loginData.code === 0 && loginData.data) {
                this.userId = loginData.data.userId;
                this.token = loginData.data.accessToken;

                console.log(`✅ 登录成功: userId=${this.userId}, token=${this.token.substring(0, 8)}...`);
                this.addTestResult('HTTP登录', true, `用户ID: ${this.userId}`);
            } else {
                throw new Error(`登录失败: ${loginData.msg || '未知错误'}`);
            }

        } catch (error) {
            console.log('❌ 登录失败:', error.message);
            this.addTestResult('HTTP登录', false, error.message);
            throw error;
        }
    }

    // 2. WebSocket连接测试
    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: WebSocket连接测试...');

        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${this.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');
                    this.addTestResult('WebSocket连接', true, '连接建立成功');

                    // 设置消息监听器
                    this.setupMessageHandler();

                    // 等待连接完全稳定
                    await this.delay(500);
                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    this.addTestResult('WebSocket连接', false, error.message);
                    reject(error);
                });

                this.ws.on('close', () => {
                    console.log('🔌 WebSocket连接已关闭');
                });

                // 连接超时
                setTimeout(() => {
                    if (this.ws.readyState === WebSocket.CONNECTING) {
                        this.ws.close();
                        reject(new Error('连接超时'));
                    }
                }, 10000);

            } catch (error) {
                reject(error);
            }
        });
    }

    // 设置消息处理器
    setupMessageHandler() {
        this.ws.on('message', (data) => {
            try {
                const message = JSON.parse(data.toString());
                console.log('📨 收到消息:', JSON.stringify(message, null, 2));

                // 根据act_id处理不同类型的响应
                this.handleWebSocketResponse(message);

            } catch (error) {
                console.error('❌ 消息解析失败:', error.message);
            }
        });
    }

    // 处理WebSocket响应
    handleWebSocketResponse(message) {
        const { act_id, code, roleList, roleCount, data, msg } = message;

        switch (act_id) {
            case 3: // 查询角色列表响应
                if (roleList && Array.isArray(roleList)) {
                    this.characters = roleList;
                    console.log(`📋 获取到${roleCount || roleList.length}个角色`);
                }
                break;

            case 4: // 角色选择响应
                if (code === 0) {
                    console.log('🎯 角色选择成功');
                }
                break;

            case 1000: // 角色信息查询响应
                this.code1000Data = {
                    act_id: message.act_id,
                    code: message.code,
                    data: message.data,
                    timestamp: new Date().toISOString()
                };
                console.log(`📊 1000指令数据接收:`, JSON.stringify(this.code1000Data, null, 2));
                break;

            case 1020: // 玩家完整信息查询响应
                this.code1020Data = {
                    act_id: message.act_id,
                    code: message.code,
                    data: message.data,
                    timestamp: new Date().toISOString()
                };
                console.log(`📊 1020指令数据接收:`, JSON.stringify(this.code1020Data, null, 2));
                break;

            default:
                // 记录其他消息但不处理
                break;
        }
    }

    // 3. 查询角色列表
    async testQueryCharacters() {
        console.log('\n📋 步骤3: 查询角色列表...');

        return new Promise(async (resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('查询角色列表', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 等待WebSocket连接稳定
            await this.delay(1000);

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.roleList && Array.isArray(message.roleList)) {
                            this.characters = message.roleList;
                            console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
                            this.addTestResult('查询角色列表', true, `获取${this.characters.length}个角色`);
                        } else {
                            this.characters = [];
                            console.log('✅ 查询成功，暂无角色');
                            this.addTestResult('查询角色列表', true, '获取0个角色');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('查询角色列表', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送查询角色列表请求
            this.ws.send(JSON.stringify({
                c: 3,
                d: null
            }));

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('查询角色列表', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    // 4. 选择角色
    async testSelectCharacter() {
        console.log('\n🎯 步骤4: 选择角色...');

        if (this.characters.length === 0) {
            console.log('⚠️ 没有可选择的角色');
            this.addTestResult('选择角色', false, '没有可用角色');
            return;
        }

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('选择角色', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 优先选择ID为2001的角色，如果没有则选择第一个
            let targetCharacter = this.characters.find(char => char.id === 2001);
            if (!targetCharacter) {
                targetCharacter = this.characters[0];
                console.log(`⚠️ 未找到ID为2001的角色，选择第一个角色: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
            } else {
                console.log(`✅ 找到目标角色: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
            }

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 4) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.code === 0) {
                            this.selectedCharacter = targetCharacter;
                            console.log(`✅ 角色选择成功: ${targetCharacter.name} (ID: ${targetCharacter.id})`);
                            this.addTestResult('选择角色', true, `选择角色: ${targetCharacter.name}`);

                            // 等待服务器处理角色选择
                            setTimeout(() => {
                                resolve();
                            }, 2000);
                        } else {
                            console.log(`❌ 角色选择失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('选择角色', false, message.msg || '选择失败');
                            resolve();
                        }
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('选择角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送选择角色请求
            this.ws.send(JSON.stringify({
                c: 4,
                d: {
                    characterId: targetCharacter.id
                }
            }));

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('选择角色', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    // 5. 测试1000指令 - 角色信息查询
    async testCode1000CharacterInfo() {
        console.log('\n📊 步骤5: 测试1000指令 - 角色信息查询...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('1000指令测试', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1000) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 1000指令调用成功');
                            console.log(`📊 角色信息:`, JSON.stringify(message.data, null, 2));

                            // 验证基础数据结构
                            if (message.data && typeof message.data === 'object') {
                                console.log('✅ 1000指令数据结构验证通过');
                                this.addTestResult('1000指令测试', true, '角色信息查询成功');
                            } else {
                                console.log('❌ 1000指令数据结构验证失败');
                                this.addTestResult('1000指令测试', false, '返回数据格式错误');
                            }
                        } else {
                            console.log(`❌ 1000指令调用失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('1000指令测试', false, message.msg || '调用失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 1000指令响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('1000指令测试', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送1000请求
            const requestData = {
                c: 1000,
                d: {}
            };

            console.log(`📤 发送1000请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('1000指令测试', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 6. 测试1020指令 - 玩家完整信息查询
    async testCode1020PlayerInfo() {
        console.log('\n📊 步骤6: 测试1020指令 - 玩家完整信息查询...');

        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            this.addTestResult('1020指令测试', false, 'WebSocket未连接');
            return;
        }

        return new Promise((resolve) => {
            let responseReceived = false;

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1020) {
                        this.ws.removeListener('message', responseHandler);
                        responseReceived = true;

                        if (message.code === 0) {
                            console.log('✅ 1020指令调用成功');
                            console.log(`📊 玩家完整信息:`, JSON.stringify(message.data, null, 2));

                            // 验证基础数据结构
                            if (message.data && typeof message.data === 'object') {
                                console.log('✅ 1020指令数据结构验证通过');
                                this.addTestResult('1020指令测试', true, '玩家完整信息查询成功');
                            } else {
                                console.log('❌ 1020指令数据结构验证失败');
                                this.addTestResult('1020指令测试', false, '返回数据格式错误');
                            }
                        } else {
                            console.log(`❌ 1020指令调用失败: ${message.msg || '未知错误'}`);
                            this.addTestResult('1020指令测试', false, message.msg || '调用失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    console.error('❌ 1020指令响应解析失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('1020指令测试', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送1020请求
            const requestData = {
                c: 1020,
                d: {
                    userId: this.selectedCharacter.id
                }
            };

            console.log(`📤 发送1020请求:`, JSON.stringify(requestData, null, 2));
            this.ws.send(JSON.stringify(requestData));

            // 设置超时
            setTimeout(() => {
                if (!responseReceived) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('1020指令测试', false, '请求超时');
                    resolve();
                }
            }, 10000);
        });
    }

    // 7. 验证教派信息返回
    async validateFactionInfo() {
        console.log('\n🔍 步骤7: 验证教派信息返回...');

        let factionInfoValid = false;
        let factionInfoMessage = '';

        // 验证1000指令中的教派信息
        if (this.code1000Data && this.code1000Data.data) {
            const religionInfo = this.code1000Data.data.religion;
            if (religionInfo) {
                console.log(`✅ 1000指令教派信息:`, JSON.stringify(religionInfo, null, 2));
                if (religionInfo.id !== undefined && religionInfo.name !== undefined) {
                    factionInfoValid = true;
                    factionInfoMessage += '1000指令教派信息正常; ';

                    // 检查是否有真实的教派信息（不是默认的"无"）
                    if (religionInfo.id > 0 && religionInfo.name !== "无") {
                        factionInfoMessage += '1000指令有真实教派信息; ';
                        console.log('🎉 1000指令返回了真实的教派信息！');
                    } else {
                        factionInfoMessage += '1000指令返回默认教派信息; ';
                        console.log('ℹ️ 1000指令返回默认教派信息（用户暂无教派）');
                    }
                } else {
                    factionInfoMessage += '1000指令教派信息格式错误; ';
                }
            } else {
                console.log('❌ 1000指令中没有教派信息');
                factionInfoMessage += '1000指令缺少教派信息; ';
            }
        }

        // 验证1020指令中的教派信息
        if (this.code1020Data && this.code1020Data.data) {
            const religionInfo = this.code1020Data.data.religion;
            if (religionInfo) {
                console.log(`✅ 1020指令教派信息:`, JSON.stringify(religionInfo, null, 2));
                if (religionInfo.id !== undefined && religionInfo.name !== undefined) {
                    factionInfoValid = true;
                    factionInfoMessage += '1020指令教派信息正常; ';

                    // 检查是否有真实的教派信息（不是默认的"无"）
                    if (religionInfo.id > 0 && religionInfo.name !== "无") {
                        factionInfoMessage += '1020指令有真实教派信息; ';
                        console.log('🎉 1020指令返回了真实的教派信息！');
                    } else {
                        factionInfoMessage += '1020指令返回默认教派信息; ';
                        console.log('ℹ️ 1020指令返回默认教派信息（用户暂无教派）');
                    }
                } else {
                    factionInfoMessage += '1020指令教派信息格式错误; ';
                }
            } else {
                console.log('❌ 1020指令中没有教派信息');
                factionInfoMessage += '1020指令缺少教派信息; ';
            }
        }

        if (factionInfoValid) {
            console.log('🎉 教派信息返回正常！');
            this.addTestResult('教派信息验证', true, factionInfoMessage);
        } else {
            console.log('⚠️ 教派信息返回异常');
            this.addTestResult('教派信息验证', false, factionInfoMessage);
        }
    }

    // 8. 断开连接
    async testDisconnect() {
        console.log('\n🔌 步骤8: 断开WebSocket连接...');
        if (this.ws) {
            this.ws.close();
        }
        this.addTestResult('断开连接', true, '连接已断开');
    }

    // 添加测试结果
    addTestResult(testName, success, message) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            timestamp: new Date().toISOString()
        });
    }

    // 打印测试结果
    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(50));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (result.success) successCount++;
        });

        console.log('='.repeat(50));
        console.log(`总计: ${successCount}/${totalCount} 项测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！教派信息修复成功！');
        } else {
            console.log('⚠️  部分测试失败，请检查日志');
        }

        // 输出教派信息对比
        if (this.code1000Data && this.code1020Data) {
            console.log('\n📋 教派信息对比:');
            console.log('='.repeat(50));
            console.log('1000指令教派信息:');
            console.log(JSON.stringify(this.code1000Data.data.religion, null, 2));
            console.log('\n1020指令教派信息:');
            console.log(JSON.stringify(this.code1020Data.data.religion, null, 2));

            // 检查两个指令的教派信息是否一致
            const religion1000 = this.code1000Data.data.religion;
            const religion1020 = this.code1020Data.data.religion;

            if (religion1000.id === religion1020.id && religion1000.name === religion1020.name) {
                console.log('\n✅ 两个指令的教派信息完全一致！');
            } else {
                console.log('\n⚠️ 两个指令的教派信息不一致！');
            }
        }
    }

    // HTTP请求工具方法
    async makeHttpRequest(path, method = 'GET', data = null) {
        return new Promise((resolve, reject) => {
            const options = {
                hostname: CONFIG.server.host,
                port: CONFIG.server.port,
                path: path,
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                }
            };

            if (data) {
                const postData = JSON.stringify(data);
                options.headers['Content-Length'] = Buffer.byteLength(postData);
            }

            const req = http.request(options, (res) => {
                let body = '';

                res.on('data', (chunk) => {
                    body += chunk;
                });

                res.on('end', () => {
                    try {
                        const responseData = JSON.parse(body);
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(responseData);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${responseData.message || body}`));
                        }
                    } catch (error) {
                        if (res.statusCode >= 200 && res.statusCode < 300) {
                            resolve(body);
                        } else {
                            reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                        }
                    }
                });
            });

            req.on('error', (error) => {
                reject(error);
            });

            if (data) {
                req.write(JSON.stringify(data));
            }

            req.end();
        });
    }

    // 延迟函数
    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 运行测试
async function main() {
    const tester = new FactionWithReligionTester();
    await tester.runTest();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = FactionWithReligionTester;
